import Vue from 'vue'
import VueRouter from 'vue-router'

import Reg from '@/views/Reg/Reg.vue'
import Login from '@/views/Login/Login.vue'
import Main from '@/views/Main/Main.vue'
import Home from '@/views/Menus/Home/Home.vue'
import ArtCate from '@/views/Menus/Art/ArtCate.vue'
import ArtList from '@/views/Menus/Art/ArtList.vue'
import UserInfo from '@/views/Menus/User/UserInfo.vue'
import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
import UserPwd from '@/views/Menus/User/UserPwd.vue'
import store from '../store/'
Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  { path: '/reg', component: Reg },
  { path: '/login', component: Login },
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      {
        path: 'home', component: Home
      },
      {
        path: '/art-cate', component: ArtCate
      },
      {
        path: '/art-list', component: ArtList
      },
      {
        path: '/user-info', component: UserInfo
      },
      {
        path: '/user-avatar', component: UserAvatar
      },
      {
        path: '/user-pwd', component: UserPwd
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (!store.state.user.token && to.path !== '/login' && to.path !== '/reg') {
    Vue.prototype.$message.error('请登录！')
    return next('/login')
  }
  next()
})

export default router
